// 数据库的操作
package storage

import (
	"multi-cloud-manage/internal/database"
	"multi-cloud-manage/internal/model"

	"gorm.io/gorm"
)

var db *gorm.DB

func init() {
	var err error
	// 数据库连接
	db, err = database.InitDB()
	if err != nil {
		panic(err)
	}
}

// 插入用户
func CreateUser(user model.User) error {
	return db.Create(&user).Error
}

// 通过用户名查询用户
func GetUserByUsername(username string) (*model.User, bool) {
	var user model.User
	err := db.Where("username = ?", username).First(&user).Error
	if err != nil {
		return nil, false
	}
	return &user, true
}

// 添加凭据
func CreateCredentials(credentials *model.UserCredentials) error {
	return db.Create(credentials).Error
}

// 查询当前用户的ak、sk
func GetAkByUserId(userId int) (*model.UserCredentials, error) {
	var uc model.UserCredentials
	err := db.Select("ak, sk").Where("user_id = ?", userId).First(&uc).Error
	if err != nil {
		return nil, err
	}
	return &uc, nil
}

// 插入ECS
func CreateEcs(ecs model.Ecs) error {
	return db.Create(&ecs).Error
}
